<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="flex" v-loading="loadingRef">
    <DeptTree class="w-1/5 xl:w-1/6" @click="handleCheck" :initCheck="false" />
    <div class="main-container">
      <CommonDateSearch ref="searchRef" @search="handleSearch" :disabledOption="['day', 'hisYear', 'custom']"
        :extraSearch="extraSearch">
      </CommonDateSearch>
      <div class="content-box">
        <div class="content-container">
          <a-card class="common-card flex chart-box" title="本周期数据">
            <template #extra>
              <a-button type="primary" @click="handleDownload">下载</a-button>
            </template>
            <Bar ref="chartRef" :chartData="chartData" title="本周期数据环比" :toolbox="toolbox" />
          </a-card>
          <div class="chart-box">
            <BasicTable ref="tableRef" @register="registerTable">
              <template #toolbar>
                <a-button type="primary" @click="handleExport" :loading="exportLoading">导出</a-button>
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts"
  setup>
  import { reactive, ref, computed } from 'vue'
  import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
  import { PageWrapper } from '@/components/Page'
  import DeptTree from '../energyComparison/DeptTree.vue'
  import { BasicTable, useTable, FormSchema } from '@/components/Table'
  import { getYoyData, ExportYoyData } from '@/api/dataReport/energyDataYOY.ts'
  // import Ratio from '@/views/dataReport/energyComparison/Ratio.vue'
  import Bar from '@/components/Charts/Bar/index.vue'
  import _ from 'lodash-es'
  import { message } from 'ant-design-vue'

  import {
    downloadByData,
  } from '@/utils/file/download';

  defineOptions({ name: 'Deviceanagement' })

  const exportLoading = ref(false)
  const toolbox = {
    show: true,
    feature: {
      saveAsImage: { show: true }
    }
  }

  let searchRef = ref()
  let chartRef = ref()
  let tableRef = ref()
  const loadingRef = ref(true)
  const chartData = ref({
    xaxisList: [],
    yaxisList: []
  })
  const searchInfo = reactive<Recordable>({})
  const [registerTable, { setColumns, setTableData }] = useTable({
    rowKey: 'id',
    title: '数据报表',
    columns: [],
    pagination: false,
    showIndexColumn: false,
    formConfig: {
      labelWidth: 120,
    },
    bordered: true,
    striped: false,
  })

  const dateNameObj = {
    week: '周',
    month: '月',
    year: '年'
  }
  const typeOptions = [
    { label: '同比', value: 0 },
    { label: '环比', value: 1 },
  ]

  const extraSearch = ref<FormSchema[]>([
    {
      field: 'homologyType',
      // label: '系统选择',
      component: 'RadioGroup',
      required: true,
      colProps: { span: 6 },
      defaultValue: 0,
      componentProps: {
        options: typeOptions,
      }
    },
  ])

  const typeName = computed(() => {
    const { homologyType } = searchInfo
    return typeOptions.filter(item => item.value === homologyType)[0].label
  });

  const handleSearch = (params) => {
    Object.assign(searchInfo, params)
    getData()
  }

  const getData = async () => {
    loadingRef.value = true
    const { classifyIdList, ...others } = searchInfo
    getYoyData({ classifyIdList: classifyIdList.join(','), ...others }).then(res => {
      setData(res)
    }).catch(() => {
      const data = {
        headers: [],
        bodyList: []
      }
      setData(data)
    }).finally(() => {
      loadingRef.value = false
    })
  }

  const setData = (data) => {
    const { homologyType } = searchInfo
    if (homologyType === 1) {
      formatQoqTableData(data)
    } else {
      formatYoyTableData(data)
    }
    formatChartData(data)
  }

  function handleCheck(keys) {
    searchInfo.classifyIdList = keys
    searchRef.value.handleSearch()
  }

  const formatChartData = (res) => {
    const { headers, bodyList } = res
    chartData.value = {
      xaxisList: headers,
      yaxisList: bodyList.map(item => ({
        name: item.name,
        data: Object.values(item.curData)
      }))
    }
  }

  const formatYoyTableData = (res) => {
    const { headers, bodyList } = res
    formatYoyHeader(headers)
    formatYoyTbody(bodyList)
  }

  const formatYoyHeader = (headers) => {
    const headerList = headers.map((item) => ({
      title: item,
      dataIndex: item,
      width: 100,
      customRender: ({ text, record }) => {
        return typeof text === 'number' ? text : '--'
      },
    }))
    headerList.unshift({
      title: '数据名称',
      dataIndex: 'name',
      width: 160,
      fixed: 'left',
      merge: true,
      customCell: (item, index) => {
        return {
          rowSpan: index % 2 ? 0 : 2,
        }
      },
    },
      {
        title: '类型',
        dataIndex: 'type',
        width: 100,
        fixed: 'left',
      })

    setColumns(headerList)
  }

  const formatYoyTbody = (bodyList) => {
    let bodyData: any[] = []
    bodyList.forEach((item: any) => {

      const { curData, radio, ...others } = item
      let recordData = { ...others, type: '数值', ...curData }
      let recordPercent = { ...others, type: typeName, ...radio }

      bodyData.push(recordData, recordPercent)
    })
    setTableData(bodyData)
  }

  const formatQoqTableData = (res) => {
    const { headers, bodyList } = res
    formatQoqHeader(headers)
    formatQoqTbody(bodyList)
  }

  const formatQoqHeader = (headers) => {
    const { queryType } = searchInfo
    const dateName = dateNameObj[queryType]
    const headerList = headers.map((item) => ({
      title: item,
      children: [
        {
          title: `上${dateName}`,
          dataIndex: `old-${item}`,
          width: 80,
          customRender: ({ text, record }) => {
            return typeof text === 'number' ? text : '--'
          },
          customCell: (item, index) => {
            const isPercentCol = typeOptions.map(item => item.label).includes(item.type)
            return {
              colSpan: isPercentCol ? 2 : 1,
            }
          },
        },
        {
          title: `本${dateName}`,
          dataIndex: `cur-${item}`,
          width: 80,
          customRender: ({ text }) => {
            return typeof text === 'number' ? text : '--'
          },
          customCell: (item, index) => {
            const isPercentCol = typeOptions.map(item => item.label).includes(item.type)
            return {
              colSpan: isPercentCol ? 0 : 1,
            }
          },
        }
      ]

    }))
    headerList.unshift({
      title: '数据名称',
      dataIndex: 'name',
      width: 160,
      fixed: 'left',
      merge: true,
      customCell: (item, index) => {
        return {
          rowSpan: index % 2 ? 0 : 2,
        }
      },
    },
      {
        title: '类型',
        dataIndex: 'type',
        width: 100,
        fixed: 'left',
      })

    setColumns(headerList)
  }

  const formatQoqTbody = (bodyList) => {
    let bodyData: any[] = []
    bodyList.forEach((item: any) => {

      const { curData, oldData, radio, ...others } = item
      let recordData = { ...others, type: '数值' }
      let recordPercent = { ...others, type: typeName }
      // 格式化本月数据
      _.forEach(curData, (value, key) => {
        recordData[`cur-${key}`] = value
      })
      // 格式化上月数据
      _.forEach(oldData, (value, key) => {
        recordData[`old-${key}`] = value
      })
      // 格式化比值为了跨列
      _.forEach(radio, (value, key) => {
        recordPercent[`old-${key}`] = value
        recordPercent[`cur-${key}`] = value
      })
      bodyData.push(recordData, recordPercent)
    })
    setTableData(bodyData)
  }

  const handleDownload = () => {
    const chart = chartRef.value.getInstance()
    var imgData = chart.getDataURL({
      pixelRatio: 2,
      backgroundColor: '#fff'
    });
    // 创建一个临时的 <a> 标签用于下载
    var link = document.createElement('a');
    link.href = imgData;
    link.download = `${searchInfo.startDay}-${typeName.value}.svg`; // 设置下载文件名
    link.click(); // 触发下载
  }

  const handleExport = async () => {
    const { classifyIdList, ...others } = searchInfo
    ExportYoyData({ classifyIdList: classifyIdList.join(','), ...others }).then(res => {
      const { data, headers } = res
      let contentDisposition = decodeURIComponent(headers["content-disposition"]);
      const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
      const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
      downloadByData(data, fileName);
      exportLoading.value = false
      message.success("导出成功");
    }).finally(() => {
      exportLoading.value = false
    })

  }
</script>
<style scoped
  lang="less">
  .main-container {
    display: flex;
    flex: 1;
    flex-direction: column;
    height: 100%;
    overflow: hidden;

    .content-box {
      display: flex;
      flex: 1;
      overflow: auto;
      background: #fff;

      .content-container {
        display: flex;
        flex: 1;
        flex-direction: column;
        margin: 8px;
        overflow: hidden;
      }

      .chart-box {
        flex: 1;
        flex-shrink: 0;

        /* min-height: 340px; */
        overflow: hidden;

        :deep(.ant-table-wrapper),
        :deep(.ant-card-head) {
          padding: 0;
        }

        :deep(.ant-card-body) {
          padding: 8px 0;
        }
      }

    }
  }
</style>
